from First.DataAccess import utils
from First import views
import requests

def yemianfenxi(start_date,end_date):
    def hanneihuoqushuju(start_date, end_date):
        access_token, appkey = utils.huoquyonghujiapi()
        method = 'visit/page/a'
        # metrics = 'pv_count'
        metrics = 'pv_count, pv_ratio, average_stay_time, stay_time_ratio, bounce_ratio'
        url = 'https://openapi.baidu.com/rest/2.0/mtj/svc/app/getDataByKey?access_token={access_token}&key={appkey}&method={method}&start-date={start_date}&end-date={end_date}&metrics={metrics}'.format(
            access_token=access_token, appkey=appkey, method=method, start_date=start_date, end_date=end_date,
            metrics=metrics)
        return request_data(url)

    str1 = hanneihuoqushuju(start_date, end_date)
    # print(str1)
    if 'error_code' in str1:
        utils.gengxinyonghujiapi()
        str1 = hanneihuoqushuju(start_date, end_date)
        if 'error_code' in str1:
            views.hanshurwzanting('rwyemianfenxi')
    if 'error_code' not in str1:
        length = len(str1['result']['items'][0])
        dataqingxi = {}
        dataqingxi['yemianmingcheng'] = []
        dataqingxi['yemianid'] = []
        dataqingxi['bieming'] = []
        dataqingxi['fangwencishu'] = []
        dataqingxi['fangwencishuzhanbi'] = []
        dataqingxi['pingjvtinngliushijian'] = []
        dataqingxi['tingliushijianzhanbi'] = []
        dataqingxi['yemiantiaochulv'] = []
        dataqingxi['sum'] = []
        for num in range(0, length):
            # print(str(str1['result']['items'][0][num][0]['pageName']))
            dataqingxi['yemianmingcheng'].append(str(str1['result']['items'][0][num][0]['pageName']))
            dataqingxi['yemianid'].append(str(str1['result']['items'][0][num][0]['pageId']))
            dataqingxi['bieming'].append(str(str1['result']['items'][0][num][0]['pageAlias']))
            dataqingxi['fangwencishu'].append(
                0 if str1['result']['items'][1][num][0] == "--" else int(str1['result']['items'][1][num][0]))
            dataqingxi['fangwencishuzhanbi'].append(
                0 if str1['result']['items'][1][num][1] == "--" else int(str1['result']['items'][1][num][1]))
            dataqingxi['pingjvtinngliushijian'].append(
                0 if str1['result']['items'][1][num][2] == "--" else int(str1['result']['items'][1][num][2]))
            dataqingxi['tingliushijianzhanbi'].append(
                0 if str1['result']['items'][1][num][3] == "--" else int(str1['result']['items'][1][num][3]))
            dataqingxi['yemiantiaochulv'].append(
                0 if str1['result']['items'][1][num][4] == "--" else int(str1['result']['items'][1][num][4]))
        fangwencishu = (str1['result']['sum'][0][0])
        fangwencishuzhanbi = (str1['result']['sum'][0][1])
        pingjvtinngliushijian = ((str1['result']['sum'][0][2]))
        tingliushijianzhanbi = ((str1['result']['sum'][0][3]))
        yemiantiaochulv = (str1['result']['sum'][0][4])
        dataqingxi['sum'].append({'fangwencishu': fangwencishu, 'fangwencishuzhanbi': fangwencishuzhanbi,
                                  'tingliushijianzhanbi': tingliushijianzhanbi,
                                  'pingjvtinngliushijian': pingjvtinngliushijian, 'yemiantiaochulv': yemiantiaochulv})
        return dataqingxi


def yemianlujing(start_date,end_date):
    def hanneihuoqushuju(start_date, end_date):
        access_token, appkey = utils.huoquyonghujiapi()
        method = 'visit/path/flow'
        url = 'https://openapi.baidu.com/rest/2.0/mtj/svc/app/getDataByKey?access_token={access_token}&key={appkey}&method={method}&start-date={start_date}&end-date={end_date}'.format(
            access_token=access_token, appkey=appkey, method=method, start_date=start_date, end_date=end_date)
        return request_data(url)

    str1 = hanneihuoqushuju(start_date, end_date)
    # print(str1)
    if 'error_code' in str1:
        utils.gengxinyonghujiapi()
        str1 = hanneihuoqushuju(start_date, end_date)
        if 'error_code' in str1:
            views.hanshurwzanting('rwyemianlujing')
    if 'error_code' not in str1:
        length = len(str1['result']['down_page'])
        dataqingxi = {}
        dataqingxi['yemianguanxi'] = []
        dataqingxi['yemianlie'] = []
        for num in range(0, length):
            length1 = len(str1['result']['down_page'][num]['items'])
            for num1 in range(0, length1):
                source = "[" + str(num + 1) + "] " + str(str1['result']['list'][num]['name'])
                target = "[" + str(num + 2) + "] " + str(str1['result']['down_page'][num]['items'][num1][0]['name'])
                value = str(str1['result']['down_page'][num]['items'][num1][1])
                dataqingxi['yemianguanxi'].append({'source': source, 'target': target, 'value': value})
                text = "".join(str(a) for a in dataqingxi['yemianlie'])
                if ((text).find(source) == -1):
                    dataqingxi['yemianlie'].append({'name': source})
                text = "".join(str(a) for a in dataqingxi['yemianlie'])
                if ((text).find(target) == -1):
                    dataqingxi['yemianlie'].append({'name': target})
        return dataqingxi

def shiyongxiguan(start_date,end_date):
    def hanneihuoqushuju(strflag,start_date, end_date):
        access_token, appkey = utils.huoquyonghujiapi()
        method = 'visit/character/a'
        metrics = 'session_count'
        flag = strflag
        url = 'https://openapi.baidu.com/rest/2.0/mtj/svc/app/getDataByKey?access_token={access_token}&key={appkey}&method={method}&start-date={start_date}&end-date={end_date}&metrics={metrics}&flag={flag}'.format(
            access_token=access_token, appkey=appkey, method=method, start_date=start_date, end_date=end_date,
            metrics=metrics, flag=flag)
        return request_data(url)

    dataqingxi = {}
    dataqingxi['depth'] = []
    dataqingxi['time'] = []
    dataqingxi['interval'] = []
    dataqingxi['frequency'] = []
    arryflag = ['depth', 'time', 'frequency']
    for xflag in arryflag:
        str1 = hanneihuoqushuju(xflag, start_date, end_date)
        # print(str1)
        if 'error_code' in str1:
            utils.gengxinyonghujiapi()
            str1 = hanneihuoqushuju(xflag, start_date, end_date)
            if 'error_code' in str1:
                views.hanshurwzanting('rwshiyongxiguan')
        if 'error_code' not in str1:
            for num in range(0, len(str1['result']['items'][0])):
                letname=str1['result']['items'][0][num][0]
                letvalue=0
                if(str1['result']['items'][1][num]):
                    letvalue=str1['result']['items'][1][num][0]
                dataqingxi[xflag].append({'name':letname,'value':letvalue})
    return dataqingxi


def request_data(url):
    req = requests.get(url, timeout=30)  # 请求连接
    req_jason = req.json()  # 获取数据
    return req_jason